package com.net.common.util;

import lombok.SneakyThrows;

import java.io.*;
import java.util.function.Supplier;

/**
 * hjh
 */
public class MessageSerializableUtils {
    /**
     * 发送消息
     *
     * @param outputStream
     * @param supplier
     * @param <T>
     * @throws IOException
     */
    @SneakyThrows
    public static <T> void sendSerializableMessage(OutputStream outputStream, Supplier<T> supplier) {
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(supplier.get());
        objectOutputStream.flush();
    }

    /**
     * 监听消息
     *
     * @param inputStream
     * @param <T>
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static <T> T listenerSerializableMessage(InputStream inputStream) throws IOException, ClassNotFoundException {
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        return (T) objectInputStream.readObject();
    }
}
